/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
import java.util.stream.Collectors;
class Solution {
    class Tuple {
        public Node node;
        public int depth;
        public Tuple(Node node, int depth) {
            this.node = node;
            this.depth = depth;
        }
    }
    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> ans = new ArrayList<>();
        if (root != null) {
            Queue<Tuple> queue = new LinkedList<>();
            queue.offer(new Tuple(root, 0));
            while (!queue.isEmpty()) {
                Tuple queueHead = queue.poll();
                if (ans.size() <= queueHead.depth) {
                    ans.add(new ArrayList<>());
                }
                List<Integer> levelList = ans.get(queueHead.depth);
                levelList.add(queueHead.node.val);
                ans.set(queueHead.depth, levelList);
                for (Node node : queueHead.node.children) {
                    queue.offer(new Tuple(node, queueHead.depth + 1));
                }
            }
        }
        return ans;
    }
}
